import {
    urlapi
} from '../apiconfig.js'
import {Toast} from 'vant';

const tips = {
    1: '抱歉，出现了一个错误',
    1005: 'appkey无效',
    3000: '期刊不存在'
}
import axios from 'axios'
import router from '../router'
// # 解构
class HTTP {
    request({
                url,
                data = {},
                method = 'POST'
            }) {
        return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method)
        })
    }

    _request(url, resolve, reject, data = {}, method = 'POST') {
        var urls = urlapi.host + urlapi.hostapi + url
        axios({
            method: method,
            url: urls,
            data: data,
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                var str = ret;
                str = (str.substring(str.length - 1) == '&') ? str.substring(0, str.length - 1) : str;
                return str
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(function (res) {
            if (res.data.code == 0) {
                Toast(res.data.msg);
            }
            if (res.data.code == 401) {
                Toast(res.data.msg);
            }
            resolve(res.data)

        }).catch(function (error) {
            console.log(error)
            if (error.response && error.response.status === 401) {
                Toast('登录信息失效，请重新登录')
                localStorage.removeItem('userinfo')
                router.replace('login')
            } else {
                Message.error(error.message);
                return Promise.reject(error.message);
            }
        })
    }

    _showerror(msg) {
        Toast(msg);
    }
}

export {
    HTTP
}
